<template>
  <section class="article-create-page">
    <el-card shadow="hover" class="article-card">
      <template #header>
        <div class="card-header">
          <span>发布文章</span>
        </div>
      </template>

      <el-form ref="formRef" :model="form" :rules="rules" label-width="96px" status-icon class="article-form">
        <el-form-item label="标题" prop="title">
          <el-input v-model.trim="form.title" placeholder="请输入文章标题" clearable />
        </el-form-item>

        <el-form-item label="分类" prop="category">
          <el-select v-model="form.category" placeholder="请选择分类" clearable>
            <el-option label="技术" value="tech" />
            <el-option label="生活" value="life" />
            <el-option label="新闻" value="news" />
          </el-select>
        </el-form-item>

        <el-form-item label="作者" prop="author">
          <el-input v-model.trim="form.author" placeholder="请输入作者名" clearable />
        </el-form-item>

        <el-form-item label="内容" prop="content">
          <!-- Markdown 编辑器 -->
          <MdEditor
            v-model="form.content"
            :preview="true"
            :editorId="editorId"
            placeholder="支持 Markdown，至少 10 字"
            @onUploadImg="handleUploadImg"
            style="min-height: 320px"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" :loading="submitting" @click="onSubmit">
            {{ submitting ? "发布中..." : "发布文章" }}
          </el-button>
          <el-button @click="onReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </section>
</template>

<script setup lang="ts">
import { reactive, ref } from "vue";
import { ElMessage } from "element-plus";
import type { FormInstance, FormRules } from "element-plus";
import { MdEditor } from "md-editor-v3";

interface CreateForm {
  title: string;
  category: "" | "tech" | "life" | "news";
  author: string;
  content: string;
}

const formRef = ref<FormInstance>();
const submitting = ref(false);
const editorId = "article-create-md";

const form = reactive<CreateForm>({
  title: "",
  category: "",
  author: "",
  content: "",
});

const rules: FormRules<CreateForm> = {
  title: [
    { required: true, message: "请填写标题", trigger: "blur" },
    { min: 2, message: "标题至少 2 个字符", trigger: "blur" },
  ],
  category: [{ required: true, message: "请选择分类", trigger: "change" }],
  author: [{ required: true, message: "请填写作者", trigger: "blur" }],
  content: [
    { required: true, message: "请填写内容", trigger: "change" },
    {
      validator: (_, value, callback) => {
        if (!value || String(value).trim().length < 10) {
          callback(new Error("内容长度至少 10 字"));
        } else {
          callback();
        }
      },
      trigger: "blur",
    },
  ],
};

// 模拟发布接口：校验 + 成功提示
function mockCreateArticle(payload: CreateForm): Promise<{ id: string }> {
  return new Promise((resolve) => setTimeout(() => resolve({ id: "a_999" }), 900));
}

// 图片上传占位（后续可对接后端）
async function handleUploadImg(files: File[], callback: (urls: string[]) => void) {
  // 这里先模拟：使用对象URL作为预览地址（页面刷新失效，仅演示）
  const urls = files.map((f) => URL.createObjectURL(f));
  callback(urls);
}

async function onSubmit() {
  if (!formRef.value) return;
  try {
    await formRef.value.validate();
  } catch {
    ElMessage.error("请完善表单信息");
    return;
  }

  submitting.value = true;
  try {
    const res = await mockCreateArticle(form);
    ElMessage.success(`发布成功（模拟后端），文章ID：${res.id}`);
  } catch (e) {
    ElMessage.error("发布失败，请稍后重试");
  } finally {
    submitting.value = false;
  }
}

function onReset() {
  form.title = "";
  form.category = "";
  form.author = "";
  form.content = "";
  formRef.value?.clearValidate();
  ElMessage.info("已重置表单");
}
</script>

<style scoped lang="scss">
.article-create-page {
  padding: 16px;
}

.article-card {
  .card-header {
    font-size: 18px;
    font-weight: 600;
  }
}

.article-form {
  :deep(.el-form-item) {
    margin-bottom: 16px;
  }
}
</style>
